package com.glela.platform.service.impl;

import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.glela.common.constant.KeepAccountsTypeConstants;
import com.glela.common.constant.StoreTypeEnum;
import com.glela.common.util.DateUtil;
import com.glela.platform.mapper.CUserMoneyChangeMapper;
import com.glela.platform.mapper.CUserPointTransactionMapper;
import com.glela.platform.mapper.MoneyBusinessTypeMapper;
import com.glela.platform.mapper.UserJournalMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.mapper.UserMoneyMapper;
import com.glela.platform.mapper.UserPointJournalMapper;
import com.glela.platform.model.CUserMoneyChange;
import com.glela.platform.model.CUserPointTransaction;
import com.glela.platform.model.MoneyBusinessType;
import com.glela.platform.model.User;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserMoney;
import com.glela.platform.model.UserPointJournal;
import com.glela.platform.service.UserMoneyService;
import com.glela.usermoney.mapper.UserCommisionMapper;
import com.glela.usermoney.model.UserCommision;

@Service
public class UserMoneyServiceImpl implements UserMoneyService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserMoneyMapper userMoneyMapper;
	@Autowired
	private CUserPointTransactionMapper pointTransactionMapper;
	@Autowired
	private UserCommisionMapper userCommisionMapper;
	@Autowired
	private UserPointJournalMapper userPointJournalMapper;
	@Autowired
	private UserJournalMapper userJournalMapper;
	@Autowired
	private MoneyBusinessTypeMapper moneyBusinessTypeMapper;
	@Autowired
	private CUserMoneyChangeMapper moneyChangeMapper;

	@Override
	public List<UserMoney> selectUserMoney(long userId) {
		return userMoneyMapper.selectByUserId(userId);
	}

	@Override
	public int freezeUserMoneyAndType(Long userId, int freezeMoney,int type) {
		UserMoney Umoney = userMoneyMapper.selectByTypeIDAndUserID(userId,type);
		if (userMapper.selectByPrimaryKey(userId) == null || Umoney == null
				|| Umoney.getNormalAmount() < freezeMoney) {
			return 0;
		}
		return userMoneyMapper.subUserMoneyByUserIDAndType(userId, freezeMoney,type);
	}

	@Override
	public int refundUserMoneyAndPointByAfterSaleSourceID(Long userId,
			Integer PointMoney, int PointMoneyBusinessType, Integer balanceMoney,
			int balanceMoneyBusinessType, Long sourceID,Integer StoreId) {
		int flag = 1;
		int[] balanceAccountsType={5,7};
		int[] pointAccountsType={14,16};
		if (PointMoney == 0 && balanceMoney == 0) {
			return flag;
		}
		User user = userMapper.selectByPrimaryKey(userId);// 当前用户
		UserMoney userAmount = userMoneyMapper.selectByTypeIDAndUserID(userId,
				1);// 账户余额
		UserMoney userPoint = userMoneyMapper
				.selectByTypeIDAndUserID(userId, 2);// 账户积分
		if (user == null || userAmount == null || userPoint == null) {
			return 0;// 账户信息找不到 找不全
		}
		if (PointMoney > 0) {// 妆币处理返还

			MoneyBusinessType moneyBusinessType = moneyBusinessTypeMapper
					.selectByTypeID(PointMoneyBusinessType);
			if (moneyBusinessType == null) {
				return 0;// 未找到对应的账务类型
			}
			CUserPointTransaction UserPointTransaction = pointTransactionMapper
					.selectBySourceIDAndBusinessType(sourceID,
							PointMoneyBusinessType);
			if (UserPointTransaction == null
					|| UserPointTransaction.getIsDelete() == 1
					|| UserPointTransaction.getTransactionStatus() ==1) {
				return 0;// 未找到对应的妆币事务 或者事务已经处理 删除
			}
			// 处理事务 生成流水信息 修改账户余额 增加账户积分信息变化记录
               
			// 处理事务 成功后插入流水
			int i = pointTransactionMapper
					.updateResultByPrimaryKey(UserPointTransaction.getId());
			if (i > 0) {
				// 处理事务成功 插入流水
				UserPointJournal pointJournal = new UserPointJournal();
				pointJournal.setValueByPointTransaction(UserPointTransaction);// 积分事务到积分记录表
				pointJournal.setBusinessSourceId(UserPointTransaction.getId());//业务源单ID
				String KeepAccountsType="";
			    //获取佣金的账务类型
				if(StoreId.intValue()==StoreTypeEnum.T14.getCode()){
					KeepAccountsType=KeepAccountsTypeConstants.POINT_SKIN79;
				}else{
					KeepAccountsType=KeepAccountsTypeConstants.POINT_NOSKIN79;
				}
				if(pointJournal.getBusinessTypeId()!=null&&
						ArrayUtils.contains(pointAccountsType, pointJournal.getBusinessTypeId().intValue())){//妆币消费
					KeepAccountsType=KeepAccountsTypeConstants.POINT_PAYMENT;
				}
				pointJournal.setKeepAccountsType(KeepAccountsType);// 财务记账类型
				userPointJournalMapper.insertSelective(pointJournal);

				UserPointJournal ResultPointJournal =
					userPointJournalMapper.selectBySourceIDAndBusinessType(
						UserPointTransaction.getId(), moneyBusinessType.getTypeId());
				if(ResultPointJournal!=null){//查到对应的处理记录了
					// 记录用户资产的变化
					CUserMoneyChange MoneyChange = new CUserMoneyChange();
					MoneyChange.setUserId(userId);
					MoneyChange.setOrderSn(ResultPointJournal.getId());// 源ID
					MoneyChange.setChangeAmount(PointMoney);
					MoneyChange.setNormalBeforAmount(userPoint.getNormalAmount());
					MoneyChange.setNormalAfterAmount(userPoint.getNormalAmount()
							+ResultPointJournal.getAmount().intValue());
					MoneyChange.setSourceType(Byte.valueOf("2"));// 积分
					MoneyChange.setFreeBeforAmount(userPoint.getFrozenAmount());
					MoneyChange.setFreeAfterAmount(userPoint.getFrozenAmount());
					MoneyChange.setChangeFreeAmount(0);
					moneyChangeMapper.insertSelective(MoneyChange);
					// 增加账户妆币
					userMoneyMapper.increaseUserAmount(
							UserPointTransaction.getUserId(), 2,
							UserPointTransaction.getAmount());
				}
			}
		}

		if (balanceMoney > 0) {// 余额处理返还
			MoneyBusinessType moneyBusinessType = moneyBusinessTypeMapper
					.selectByTypeID(balanceMoneyBusinessType);
			if (moneyBusinessType == null) {
				return 0;// 未找到对应的账务类型
			}
			UserCommision UserCommisionTransaction =
		userCommisionMapper.selectBySourceIDAndBusinessType(sourceID,balanceMoneyBusinessType);
			if (UserCommisionTransaction == null
					|| UserCommisionTransaction.getResult()!=0 
					|| UserCommisionTransaction.getStatus()!=0) {
				return 0;// 未找到对应的余额事务 或者事务已经处理 删除
			}
			// 处理事务 生成流水信息 修改账户余额 增加账户积分信息变化记录

			// 处理事务 成功后插入流水
			int i = 
			userCommisionMapper.updateResultByPrimaryKey(UserCommisionTransaction.getId());
			if (i > 0) {
				// 处理事务成功 插入流水
				UserJournal balanceJournal=new UserJournal();
				balanceJournal.setUserId(UserCommisionTransaction.getUserId()); 
				balanceJournal.setOrderSn(String.valueOf(sourceID)); //售后单ID
				balanceJournal.setMoney(UserCommisionTransaction.getFee()); 
				balanceJournal.setType("+");
				balanceJournal.setComment("售后返还余额");
				balanceJournal.setStatus(6);//系统返还
				balanceJournal.setBusinessTypeId(UserCommisionTransaction.getBusinessTypeId());
				balanceJournal.setBusinessTypeName(UserCommisionTransaction.getBusinessTypeName()); 
				balanceJournal.setIsDelete(0);
				balanceJournal.setCommisionId(UserCommisionTransaction.getId().intValue());
				String KeepAccountsType="";
			    //获取佣金的账务类型
				if(StoreId.intValue()==StoreTypeEnum.T14.getCode()){
					KeepAccountsType=KeepAccountsTypeConstants.COMMISSION_SKIN79;
				}else{
					KeepAccountsType=KeepAccountsTypeConstants.COMMISSION_NOSKIN79;
				}
				if(ArrayUtils.contains(balanceAccountsType,balanceJournal.getBusinessTypeId())){//余额消费
					KeepAccountsType=KeepAccountsTypeConstants.COMMISSION_PAYMENT;
				}
				balanceJournal.setKeepAccountsType(KeepAccountsType);
				userJournalMapper.insertSelective(balanceJournal);
				
				UserJournal ResultBalanceJournal=
					userJournalMapper.getUserJournalBySourceIDandBusinessType(
					UserCommisionTransaction.getId(),UserCommisionTransaction.getBusinessTypeId());
				if(ResultBalanceJournal!=null){//生成流水成功
					// 记录用户资产的变化
					CUserMoneyChange MoneyChange = new CUserMoneyChange();
					MoneyChange.setUserId(userId);
					MoneyChange.setOrderSn((long)ResultBalanceJournal.getId());// 源ID
					MoneyChange.setChangeAmount(balanceMoney);
					MoneyChange.setNormalBeforAmount(userAmount.getNormalAmount());
					MoneyChange.setNormalAfterAmount(userAmount.getNormalAmount()
							+ ResultBalanceJournal.getMoney());
					MoneyChange.setSourceType(Byte.valueOf("1"));//amount
					MoneyChange.setFreeBeforAmount(userAmount.getFrozenAmount());
					MoneyChange.setFreeAfterAmount(userAmount.getFrozenAmount());
					MoneyChange.setChangeFreeAmount(0);
					moneyChangeMapper.insertSelective(MoneyChange);
					// 增加账户amount
					userMoneyMapper.increaseUserAmount(
							UserCommisionTransaction.getUserId(), 1,
							UserCommisionTransaction.getFee());
				}
			}
		}
		return 1;
	}
	
	@Override
	public int refundUserMoneyAndPointByorderObjectID(Long userId,
			Integer PointMoney, int PointMoneyBusinessType, Integer balanceMoney,
			int balanceMoneyBusinessType, Long orderObjectID) {
		int flag = 1;
		if (PointMoney == 0 && balanceMoney == 0) {
			return flag;
		}
		User user = userMapper.selectByPrimaryKey(userId);// 当前用户
		UserMoney userAmount = userMoneyMapper.selectByTypeIDAndUserID(userId,
				1);// 账户余额
		UserMoney userPoint = userMoneyMapper
				.selectByTypeIDAndUserID(userId, 2);// 账户积分
		if (user == null || userAmount == null || userPoint == null) {
			return 0;// 账户信息找不到 找不全
		}
		if (PointMoney > 0) {// 妆币处理返还

			MoneyBusinessType moneyBusinessType = moneyBusinessTypeMapper
					.selectByTypeID(PointMoneyBusinessType);
			if (moneyBusinessType == null) {
				return 0;// 未找到对应的账务类型
			}
				//插入流水
				UserPointJournal pointJournal = new UserPointJournal();
				pointJournal.setUserId(userPoint.getUserId());//发生用户ID
				pointJournal.setBusinessTypeId(moneyBusinessType.getTypeId());//业务类型ID
				pointJournal.setBusinessTypeName(moneyBusinessType.getTypeName());//业务类型名称
				pointJournal.setAmount(PointMoney.longValue());//发生金额 允许负数
				pointJournal.setIsCustom(0);//是否手工处理单据
				pointJournal.setIsDelete(0);//是否删除 0 未删除 1已删除
				pointJournal.setBusinessSourceId(orderObjectID);//业务源单ID
				pointJournal.setKeepAccountsType(moneyBusinessType.getAccountsTypeComment());// 财务记账类型
				userPointJournalMapper.insertSelective(pointJournal);

				UserPointJournal resultUserPointJournal=
				userPointJournalMapper.selectBySourceIDAndBusinessType(orderObjectID, moneyBusinessType.getTypeId());
				if(resultUserPointJournal==null){
					return 0;//流水插入失败
				}
				// 记录用户资产的变化
				CUserMoneyChange MoneyChange = new CUserMoneyChange();
				MoneyChange.setUserId(userId);
				MoneyChange.setOrderSn(resultUserPointJournal.getId());// 源ID
				MoneyChange.setChangeAmount(PointMoney);
				MoneyChange.setNormalBeforAmount(userPoint.getNormalAmount());
				MoneyChange.setNormalAfterAmount(userPoint.getNormalAmount()
						+ resultUserPointJournal.getAmount().intValue());
				MoneyChange.setSourceType(Byte.valueOf("2"));// 积分
				moneyChangeMapper.insertSelective(MoneyChange);
				// 增加账户妆币
				userMoneyMapper.increaseUserAmount(
						userId, 2,resultUserPointJournal.getAmount());
			}

		if (balanceMoney > 0) {// 余额处理返还
			MoneyBusinessType moneyBusinessType = moneyBusinessTypeMapper
					.selectByTypeID(balanceMoneyBusinessType);
			if (moneyBusinessType == null) {
				return 0;// 未找到对应的账务类型
			}
				//插入流水
				UserJournal balanceJournal=new UserJournal();
				balanceJournal.setUserId(userId); 
				balanceJournal.setMoney(balanceMoney); 
				balanceJournal.setType("+");
				balanceJournal.setComment("取消订单返还余额");
				balanceJournal.setStatus(6);//系统返还
				balanceJournal.setBusinessTypeId(moneyBusinessType.getTypeId());
				balanceJournal.setBusinessTypeName(moneyBusinessType.getTypeName()); 
				balanceJournal.setIsDelete(0);
				balanceJournal.setCommisionId(orderObjectID.intValue());
				balanceJournal.setKeepAccountsType(moneyBusinessType.getKeepAccountsType());
				userJournalMapper.insertSelective(balanceJournal);
				
				UserJournal ResultBalanceJournal=
					userJournalMapper.getUserJournalBySourceIDandBusinessType(orderObjectID, moneyBusinessType.getTypeId());
				if(ResultBalanceJournal==null){
					return 0;//插入流水失败
				}
				// 记录用户资产的变化
				CUserMoneyChange MoneyChange = new CUserMoneyChange();
				MoneyChange.setUserId(userId);
				MoneyChange.setOrderSn((long)ResultBalanceJournal.getId());// 源ID
				MoneyChange.setChangeAmount(balanceMoney);
				MoneyChange.setNormalBeforAmount(userAmount.getNormalAmount());
				MoneyChange.setNormalAfterAmount(userAmount.getNormalAmount()
						+ ResultBalanceJournal.getMoney());
				MoneyChange.setSourceType(Byte.valueOf("1"));//amount
				moneyChangeMapper.insertSelective(MoneyChange);
				// 增加账户余额
				userMoneyMapper.increaseUserAmount(
						userId, 1,ResultBalanceJournal.getMoney());
			}
		return 1;
	}

	@Override
	public int batchUpdateMoneyWithJournal(List<UserJournal> userJournalList){
			// 增加账户余额
		return userMoneyMapper.BatchIncreaseUserAmount(userJournalList);
	}

	@Override
	public int batchUpdatePointWithJournal(
			List<UserPointJournal> userPointJournalList) {
		// 增加账户妆币
		return userMoneyMapper.BatchIncreaseUserPoint(userPointJournalList);
	}

	@Override
	public boolean updateFreezeAmount(long id, long userId, long freezeAmount) {
		if (id <= 0 || userId <= 0 || freezeAmount <= 0) {
			return false;
		}
		return userMoneyMapper.updateFreezeAmount(id, userId, freezeAmount) == 1;
	}

	@Override
	public boolean updateSubNormalAmount(long id, Long userId, long normalAmount) {
		if (id <= 0 || userId <= 0 || normalAmount <= 0) {
			return false;
		}
		return userMoneyMapper.updateSubNormalAmount(id, userId, normalAmount) == 1;
	}

	@Override
	public boolean updateSubFrozenAmount(long id, Long userId, Integer frozenAmount) {
		if (id <= 0 || userId <= 0 || frozenAmount <= 0) {
			return false;
		}
		return userMoneyMapper.updateSubFrozenAmount(id, userId, frozenAmount) == 1;
	}

	@Override
	public boolean updateReleaseFreezeAmount(long id, Long userId, Integer releaseFreezeAmount) {
		if (id <= 0 || userId <= 0 || releaseFreezeAmount <= 0) {
			return false;
		}
		return userMoneyMapper.updateReleaseFreezeAmount(id, userId, releaseFreezeAmount) == 1;
	}
	
	@Override
	public void checkExistUserMoney(long userId) {
		List<UserMoney> userMoneyList = this.userMoneyMapper.selectByUserId(userId);
		// 如果不存在，则添加两条
		if(CollectionUtils.isEmpty(userMoneyList)){
			UserMoney userMoney1 = new UserMoney();
			userMoney1.setUserId(userId);
			userMoney1.setType(1);
			userMoney1.setNormalAmount(0l);
			userMoney1.setFrozenAmount(0l);
			userMoney1.setCreateTime(DateUtil.parse(DateUtil.currentStringDate()));
			this.userMoneyMapper.insertSelective(userMoney1);
			UserMoney userMoney2 = new UserMoney();
			userMoney2.setUserId(userId);
			userMoney2.setType(2);
			userMoney2.setNormalAmount(0l);
			userMoney2.setFrozenAmount(0l);
			userMoney2.setCreateTime(DateUtil.parse(DateUtil.currentStringDate()));
			this.userMoneyMapper.insertSelective(userMoney2);
		}
	}
}
